const Packet = require("./packet");
const {stringToBytes, parseBitPacket, bytes2string} = require("./utils");
class SearchPacket  {
    constructor() {}

    build(
        v,
        message_type,
        sender_name,
        origin_peer_address,
        origin_peer_port,
        image_type,
        image_file_name
    ) {
        const packet = new Packet();
        let origin_peer_address_numbers = origin_peer_address.split(".").map(item => Number(item));
        packet
            .fill(v, 4)
            .fill(message_type, 8)
            .fill(0, 8)
            .fill(sender_name.length * 8, 12)
            .fillChunk(stringToBytes(sender_name), sender_name.length * 8)
            .fill(origin_peer_address_numbers[0], 8)
            .fill(origin_peer_address_numbers[1], 8)
            .fill(origin_peer_address_numbers[2], 8)
            .fill(origin_peer_address_numbers[3], 8)
            .fill(origin_peer_port, 16);
        if (typeof image_type !== 'undefined') {
            packet
                .fill(image_type, 4)
                .fill(image_file_name.length * 8, 28)
                .fillChunk(stringToBytes(image_file_name), image_file_name.length * 8);
        }
        return new Uint8Array(packet.getPacket());
    }

    parse(p) {
        let v,
            message_type,
            reserved,
            sender_name_length,
            sender_name,
            origin_peer_address,
            origin_peer_port,
            image_type,
            image_file_name_size,
            image_file_name;

        let packet = new Packet(p);

        v = packet.extract(4);
        message_type = packet.extract(8);
        reserved = packet.extract(8);
        sender_name_length = packet.extract(12);
        sender_name = bytes2string(packet.extractChunk(sender_name_length));
        origin_peer_address = packet.extractChunk(32).join(".");
        origin_peer_port = packet.extract(16);
        image_type = packet.extract(4);
        image_file_name_size = packet.extract(28);
        image_file_name = bytes2string(packet.extractChunk(image_file_name_size));

        return {
            v,
            message_type,
            reserved,
            sender_name,
            origin_peer_address,
            origin_peer_port,
            image_type,
            image_file_name
        }

    }
}

module.exports = new SearchPacket();

